import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: 'http://localhost:7777',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加token
    config.headers.token = localStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  //  响应失败的拦截器
  error => {
    // console.dir(error)
    if (error.response.status === 401) {
      //  token过期了
      router.push('/login')
      Message.error('登录已失效，请重新登录')
    }
    return Promise.reject(error)
  }
)

export default service
